package com.wao.information.web.rest;

import com.codahale.metrics.annotation.Timed;
import com.wao.information.service.InformationService;
import com.wao.information.service.dto.InformationDTO;
import com.wao.information.web.rest.util.HeaderUtil;
import com.wao.information.web.rest.util.PaginationUtil;
import io.github.jhipster.web.util.ResponseUtil;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Optional;

/**
 * REST controller for managing Information.
 */
@RestController
@RequestMapping("/api")
public class InformationResource {

    private final Logger log = LoggerFactory.getLogger(InformationResource.class);

    private static final String ENTITY_NAME = "information";

    private final InformationService informationService;

    public InformationResource(InformationService informationService) {
        this.informationService = informationService;
    }

    /**
     * POST  /information : Create a new information.
     *
     * @param informationDTO the informationDTO to create
     * @return the ResponseEntity with status 201 (Created) and with body the new informationDTO, or with status 400 (Bad Request) if the information has already an ID
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PostMapping("/information")
    @Timed
    public ResponseEntity<InformationDTO> createInformation(@Valid @RequestBody InformationDTO informationDTO) throws URISyntaxException {
        log.debug("REST request to save Information : {}", informationDTO);
        if (informationDTO.getId() != null) {
            return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert(ENTITY_NAME, "idexists", "A new information cannot already have an ID")).body(null);
        }
        InformationDTO result = informationService.save(informationDTO);
        return ResponseEntity.created(new URI("/api/information/" + result.getId()))
                .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
                .body(result);
    }

    /**
     * PUT  /information : Updates an existing information.
     *
     * @param informationDTO the informationDTO to update
     * @return the ResponseEntity with status 200 (OK) and with body the updated informationDTO,
     * or with status 400 (Bad Request) if the informationDTO is not valid,
     * or with status 500 (Internal Server Error) if the informationDTO couldn't be updated
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PutMapping("/information")
    @Timed
    public ResponseEntity<InformationDTO> updateInformation(@Valid @RequestBody InformationDTO informationDTO) throws URISyntaxException {
        log.debug("REST request to update Information : {}", informationDTO);
        if (informationDTO.getId() == null) {
            return createInformation(informationDTO);
        }
        InformationDTO result = informationService.save(informationDTO);
        return ResponseEntity.ok()
                .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, informationDTO.getId().toString()))
                .body(result);
    }

    /**
     * GET  /information : get all the information.
     *
     * @param pageable the pagination information
     * @return the ResponseEntity with status 200 (OK) and the list of information in body
     */
    @GetMapping("/information")
    @Timed
    public ResponseEntity<List<InformationDTO>> getAllInformation(@ApiParam Pageable pageable) {
        log.debug("REST request to get a page of Information");
        Page<InformationDTO> page = informationService.findAll(pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/information");
        return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
    }

    /**
     * GET  /information/:id : get the "id" information.
     *
     * @param id the id of the informationDTO to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the informationDTO, or with status 404 (Not Found)
     */
    @GetMapping("/information/{id}")
    @Timed
    public ResponseEntity<InformationDTO> getInformation(@PathVariable Long id) {
        log.debug("REST request to get Information : {}", id);
        InformationDTO informationDTO = informationService.findOne(id);
        return ResponseUtil.wrapOrNotFound(Optional.ofNullable(informationDTO));
    }

    /**
     * DELETE  /information/:id : delete the "id" information.
     *
     * @param id the id of the informationDTO to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @DeleteMapping("/information/{id}")
    @Timed
    public ResponseEntity<Void> deleteInformation(@PathVariable Long id) {
        log.debug("REST request to delete Information : {}", id);
        informationService.delete(id);
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
    }

    /**
     * GET  /categories/{id}/information : get a list of Information by CategoryId.
     *
     * @param id the categoryId of a information
     * @return the ResponseEntity with status 200 (OK) and the list of information in body
     */
    @GetMapping("/categories/{id}/information")
    @Timed
    public ResponseEntity<Page<InformationDTO>> getAllInformation(@PathVariable Long id,
                                                                  @ApiParam @PageableDefault(sort = {"displayOrder"},
                                                                          direction = Sort.Direction.ASC) Pageable pageable) {
        log.debug("REST request to get a list of Information by Category : {}", id);
        Page<InformationDTO> page = informationService.findByCategory(id, pageable);
        return new ResponseEntity<>(page, HttpStatus.OK);
    }

    /**
     * GET  /information/{id}/next : get the next information.
     *
     * @param pageable the pagination information
     * @return the ResponseEntity with status 200 (OK) and with body the informationDTO, or with status 404 (Not Found)
     */
    @GetMapping("/information/{id}/next")
    @Timed
    public ResponseEntity<InformationDTO> getNextInformation(@PathVariable Long id,
                                                             @ApiParam @PageableDefault(size = 2, sort = {"displayOrder"},
                                                                     direction = Sort.Direction.ASC) Pageable pageable) {
        log.debug("REST request to get next for Information: {}", id);
        InformationDTO informationDTO = informationService.findNext(id, pageable);
        return new ResponseEntity<>(informationDTO, HttpStatus.OK);
    }

    /**
     * GET  /information : get all the information by keyword.
     *
     * @param pageable the pagination information
     * @return the ResponseEntity with status 200 (OK) and the list of information in body
     */
    @GetMapping("/information/page")
    @Timed
    public ResponseEntity<Page<InformationDTO>> getAllInformationByPage(
            @RequestParam(name = "keyword", required = false) String keyword,
            @RequestParam(name = "categoryId", required = false) Long categoryId,
            @ApiParam Pageable pageable) {
        log.debug("REST request to get a page of Information by keyword");
        Page<InformationDTO> page = informationService.findByKeyword(keyword, categoryId, pageable);
        return new ResponseEntity<>(page, HttpStatus.OK);
    }
}
